﻿using System;
using System.Collections.Generic;
using System.Collections.Specialized;
using System.IO;
using System.Security.Cryptography;
using System.Text;
using System.Text.RegularExpressions;
using System.Web;
using System.Web.Script.Serialization;
using System.Web.SessionState;

namespace Uranus.Common
{
    public class CodeCommon
    {
        public static Regex BlankRegex = new Regex(@"\s");
        private static Random ran = new Random();
        /// <summary>
        /// 加密
        /// </summary>
        /// <param name="str"></param>
        /// <returns></returns>
        public static string HavUrlEncoder(string str)
        {
            return AddAnyStr(GetOrder(HttpUtility.UrlEncode(str))).Replace("\0", "");
        }
        /// <summary>
        /// 解密
        /// </summary>
        /// <param name="str"></param>
        /// <returns></returns>
        public static string HavUrlDncoder(string str)
        {
            return HttpUtility.UrlDecode(GetOrder(SubAnyStr(str)));
        }
        /// <summary>
        /// 加密
        /// </summary>
        /// <param name="str"></param>
        /// <returns></returns>
        public static string Encoder(string str)
        {
            return AddAnyStr(GetOrder((str))).Replace("\0", "");
        }
        /// <summary>
        /// 解密
        /// </summary>
        /// <param name="str"></param>
        /// <returns></returns>
        public static string Dncoder(string str)
        {
            return GetOrder(SubAnyStr(str));
        }
        /// <summary>
        /// 倒序
        /// </summary>
        /// <param name="str"></param>
        /// <returns></returns>
        private static string GetOrder(string str)
        {
            char a;
            char[] arr = str.ToCharArray();
            for (int i = 0; i < (arr.Length / 2); i++)
            {
                a = arr[i];
                arr[i] = arr[arr.Length - i - 1];
                arr[arr.Length - i - 1] = a;
            }
            return new string(arr);
        }
        /// <summary>
        /// 在每三个位置插入随机字母
        /// </summary>
        /// <param name="str"></param>
        /// <returns></returns>
        private static string AddAnyStr(string str)
        {
            string s = "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789";
            char[] a = new char[str.Length + str.Length / 3 + 1];
            int index = 0;
            for (int i = 0; i < str.Length; i++)
            {
                a[index++] = str[i];
                if (i % 3 == 0)
                {
                    a[index++] = s[ran.Next(0, 61)];
                }
            }
            return new string(a);
        }
        /// <summary>
        /// 去掉每三个位置的字符
        /// </summary>
        /// <param name="str"></param>
        /// <returns></returns>

        private static string SubAnyStr(string str)
        {
            for (int i = 0; i < str.Length; i++)
            {
                if (i % 3 == 0)
                {
                    if ((i + 1) < str.Length)
                        str = str.Remove((i + 1), 1);
                }
            }
            return str;
        }
        /// <summary>
        ///  获取字符串的md5
        /// </summary>
        /// <param name="str"></param>
        /// <returns></returns>
        public static string getStringCode(string str)
        {
            MD5 md5 = MD5.Create();
            byte[] bts = System.Text.Encoding.UTF8.GetBytes(str);
            bts = md5.ComputeHash(bts);
            StringBuilder sb = new StringBuilder();
            for (int i = 0; i < bts.Length; i++)
            {
                sb.Append(bts[i].ToString("x2"));
            }
            md5.Clear();
            return sb.ToString();
        }
        /// <summary>
        /// 获取文件的md5
        /// </summary>
        /// <param name="path"></param>
        /// <returns></returns>
        public static string getFileCode(string path)
        {
            MD5 md5 = MD5.Create();
            using (FileStream fs = File.OpenRead(path))
            {
                byte[] bts = md5.ComputeHash(fs);
                StringBuilder sb = new StringBuilder();
                for (int i = 0; i < bts.Length; i++)
                {
                    sb.Append(bts[i].ToString("x2"));
                }
                md5.Clear();
                return sb.ToString();
            }
        }
        /// <summary>
        /// url解码
        /// </summary>
        /// <param name="str"></param>
        /// <returns></returns>
        public static string UrlDeCode(string str)
        {
            Encoding encoding = null;
            Encoding utf8 = Encoding.UTF8;
            //首先用utf-8进行解码                    
            string code = HttpUtility.UrlDecode(str.ToUpper(), utf8);
            //将已经解码的字符再次进行编码.
            string encode = HttpUtility.UrlEncode(code, utf8).ToUpper();
            if (str == encode)
                encoding = Encoding.UTF8;
            else
                encoding = Encoding.GetEncoding("gb2312");

            return HttpUtility.UrlDecode(str, encoding);
        }

        /// <summary>
        /// 序列化
        /// </summary>
        public static string Serialize(object obj)
        {
            if (obj != null)
                return Newtonsoft.Json.JsonConvert.SerializeObject(obj);
            else return string.Empty;
        }

        /// <summary>
        /// 反序列化
        /// </summary>
        /// <typeparam name="T"></typeparam>
        /// <param name="str"></param>
        /// <returns></returns>
        public static T DeSerialize<T>(string str)
        {
            if (!string.IsNullOrEmpty(str))
            {
                return Newtonsoft.Json.JsonConvert.DeserializeObject<T>(str);
            }
            else
            {
                return default(T);
            }
        }

        /// <summary>
        /// urlcode解码
        /// </summary>
        /// <param name="str"></param>
        /// <returns></returns>
        public static string UrlUtilityDeCode(string str)
        {
            return HttpUtility.UrlDecode(str);
        }
        /// <summary>
        /// urlencode编码
        /// </summary>
        /// <param name="str"></param>
        /// <returns></returns>
        public static string UrlUtilityEnCode(string str)
        {
            return HttpUtility.UrlEncode(str);
        }

        /// <summary>
        /// c# md5
        /// </summary>
        /// <param name="code"></param>
        /// <returns></returns>
        public static string GetMD5Code(string code)
        {
            byte[] textBytes = System.Text.Encoding.Default.GetBytes(code);
            try
            {
                System.Security.Cryptography.MD5CryptoServiceProvider cryptHandler;
                cryptHandler = new System.Security.Cryptography.MD5CryptoServiceProvider();
                byte[] hash = cryptHandler.ComputeHash(textBytes);
                string ret = "";
                foreach (byte a in hash)
                {
                    ret += a.ToString("x");
                }
                return ret;
            }
            catch
            {
                throw;
            }
        }
        /// <summary>
        /// php md5
        /// </summary>
        /// <param name="code"></param>
        /// <returns></returns>
        public static string GetPhpMD5Code(string code)
        {
            byte[] textBytes = System.Text.Encoding.Default.GetBytes(code);
            try
            {
                System.Security.Cryptography.MD5CryptoServiceProvider cryptHandler;
                cryptHandler = new System.Security.Cryptography.MD5CryptoServiceProvider();
                byte[] hash = cryptHandler.ComputeHash(textBytes);
                string ret = "";
                foreach (byte a in hash)
                {
                    if (a < 16)
                        ret += "0" + a.ToString("x");
                    else
                        ret += a.ToString("x");
                }
                return ret;
            }
            catch
            {
                throw;
            }
        }

        /// <summary>
        /// 获取金额的小数点前后的分割数据
        /// </summary>
        /// <param name="str"></param>
        /// <returns></returns>
        public static string[] GetPriceData(decimal str)
        {
            return str.ToString("f2").Split('.');
        }

        public static string GetCurrentDate()
        {
            int h = DateTime.Now.Hour;
            if (h >= 5 && h < 9)
            {
                return "早上";
            }
            else if (h >= 9 && h < 11)
            {
                return "上午";
            }
            else if (h >= 11 && h < 15)
            {
                return "中午";
            }
            else if (h >= 15 && h < 19)
            {
                return "下午";
            }
            return "晚上";
        }
        /// <summary>
        /// MD5 16位加密
        /// </summary>
        /// <param name="ConvertString"></param>
        /// <returns></returns>
        public static string GetMd5Str()
        {

            MD5CryptoServiceProvider md5 = new MD5CryptoServiceProvider();
            string t2 = BitConverter.ToString(md5.ComputeHash(UTF8Encoding.Default.GetBytes(Guid.NewGuid().ToString())), 4, 8);
            t2 = t2.Replace("-", "");
            return t2;
        }
        /// <summary>
        /// 生成流水号
        /// </summary>
        /// <param name="dt">时间</param>
        /// <param name="id">id</param>
        /// <returns>长度为16位的流水号</returns>
        public static string GetSerialNumber(DateTime dt, string id)
        {
            if (!string.IsNullOrEmpty(id))
            {
                string str = "00000000";
                if (id.Length <= 8)
                {
                    str = str.Substring(0, 8 - id.Length) + id;
                }
                else
                {
                    str = id.Substring(0, 8);
                }
                return dt.ToString("yyyyMMdd") + str;
            }
            return null;
        }
        /// <summary>
        /// 获取sha1加密
        /// </summary>
        /// <param name="text"></param>
        /// <returns></returns>
        public static string GetSHA1(string text)
        {
            byte[] cleanBytes = Encoding.Default.GetBytes(text);
            byte[] hashedBytes = System.Security.Cryptography.SHA1.Create().ComputeHash(cleanBytes);
            return BitConverter.ToString(hashedBytes).Replace("-", "");
        }
        /// <summary>  
        /// 将c# DateTime时间格式转换为Unix时间戳格式  
        /// </summary>  
        /// <param name="time">时间</param>  
        /// <returns>double</returns>  
        public static int ConvertDateTimeInt(System.DateTime time)
        {
            int intResult = 0;
            System.DateTime startTime = TimeZone.CurrentTimeZone.ToLocalTime(new System.DateTime(1970, 1, 1));
            intResult = (int)(time - startTime).TotalSeconds;
            return intResult;
        }
        /// <summary>  
        /// 将Unix时间戳格式转换为c# DateTime时间格式  
        /// </summary>  
        /// <param name="timeStamp">时间戳</param>  
        /// <returns>DateTime </returns>  
        public static DateTime GetTime(string timeStamp)
        {
            DateTime dtStart = TimeZone.CurrentTimeZone.ToLocalTime(new DateTime(1970, 1, 1));
            long lTime = long.Parse(timeStamp + "0000000");
            TimeSpan toNow = new TimeSpan(lTime);
            return dtStart.Add(toNow);
        }

        /// <summary>
        /// Base64加密，解密方法
        /// </summary>
        /// <param name="str">输入字符串</param>
        /// <param name="c">true-加密,false-解密</param>
        public static string Getbase64(string str, bool isEncrypt)
        {
            if (isEncrypt)
            {
                return System.Convert.ToBase64String(System.Text.Encoding.Default.GetBytes(str));
            }
            else
            {
                //注：在进行解码时，需要输入参数s为base-64编码格式，如果不是，将抛出异常。
                //所以，需要用try捕捉一下错误。
                //红色代码处，改成
                try
                {
                    return System.Text.Encoding.Default.GetString(System.Convert.FromBase64String(str));
                }
                catch (Exception exp)
                {
                    return null;
                }
            }
        }

        /// <summary>
        /// 转换参数
        /// </summary>
        /// <returns></returns>
        public static Dictionary<string, object> ConvertParams(HttpRequestBase httpRequest)
        {
            NameValueCollection nameValueCollection = new NameValueCollection();
            foreach (var VARIABLE in httpRequest.QueryString.AllKeys)
            {
                nameValueCollection.Add(VARIABLE, httpRequest.QueryString[VARIABLE]);
            }
            foreach (var VARIABLE in httpRequest.Form.AllKeys)
            {
                nameValueCollection.Add(VARIABLE, httpRequest.Form[VARIABLE]);
            }
            return ConvertParamsByNameValue(nameValueCollection);
        }

        /// <summary>
        /// 转换参数
        /// </summary>
        /// <returns></returns>
        public static Dictionary<string, object> ConvertParams(HttpRequest httpRequest)
        {
            NameValueCollection nameValueCollection = new NameValueCollection();
            foreach (var VARIABLE in httpRequest.QueryString.AllKeys)
            {
                nameValueCollection.Add(VARIABLE, httpRequest.QueryString[VARIABLE]);
            }
            foreach (var VARIABLE in httpRequest.Form.AllKeys)
            {
                nameValueCollection.Add(VARIABLE, httpRequest.Form[VARIABLE]);
            }
            return ConvertParamsByNameValue(nameValueCollection);
        }

        private static Dictionary<string, object> ConvertParamsByNameValue(NameValueCollection nameValueCollection)
        {
            Dictionary<string, object> dicParms = new Dictionary<string, object>();
            if (nameValueCollection.Keys.Count > 0)
            {
                foreach (var p in nameValueCollection.AllKeys)
                {
                    if (p != null)
                    {
                        if (!dicParms.ContainsKey(p))
                        {
                            dicParms.Add(p.ToLower(), nameValueCollection[p]);
                        }
                        else
                        {
                            dicParms[p] = nameValueCollection[p];
                        }
                    }
                }
            }
            return dicParms;
        }

        ///生成随机数字组合
        public static byte[] GetRandomCharArrayAANumber(int count)
        {

            int number;
            string checkCode = String.Empty; //存放随机码的字符串    


            System.Random random = new Random();
            for (int i = 1; i <= count; i++) //产生N位校验码    
            {

                number = random.Next();
                number = number % 10;

                number += 48; //数字0-9编码在48-57    


                checkCode += ((char)number).ToString();
            }

            return System.Text.Encoding.Default.GetBytes(checkCode);
        }

        #region 解析url参数返回Json
        /// <summary>
        /// 解析url参数返回Json
        /// </summary>
        /// <param name="url">传入URL 可只有参数b=c 或a?b=c形式</param>
        /// <returns></returns>
        public static Dictionary<string, object> GetUrlParams(string url)
        {
            Dictionary<string, object> dic = new Dictionary<string, object>();
            try
            {
                if (string.IsNullOrEmpty(url))
                    return null;
                int questionMarkIndex = url.IndexOf('?');
                string ps = url;
                if (questionMarkIndex > -1)
                {
                    ps = url.Substring(questionMarkIndex + 1);
                }
                // 开始分析参数对  
                Regex re = new Regex(@"(^|&)?(\w+)=([^&]+)(&|$)?", RegexOptions.Compiled);
                MatchCollection mc = re.Matches(ps);
                foreach (Match m in mc)
                {
                    dic.Add(m.Result("$2").ToLower(), m.Result("$3"));
                }
            }
            catch
            {
                return null;
            }
            return dic;
        }
        #endregion
    }
}
